<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Service;

use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\WebSocketServer\Context;

class WebSocketGlobalController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public const REDIS_FD_USER_KEY = 'Remit_WebSocketGlobalController_fd_with_user_id';


    public const SUCCESS = '0_SUCCESS';

    public function onMessage($server, $frame): void
    {
        // 解析传过来的参数
        $data = json_decode($frame->data, true);

        // 是不是心跳包
        if (isset($data['type']) && $data['type'] == 'Ping') {
            if($server->exist($frame->fd)) {
                $server->push($frame->fd, 'Pong');
            }
        }
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        ApplicationContext::getContainer()->get(\Redis::class)->del(
            self::REDIS_FD_USER_KEY . $fd
        );
    }

    public function onOpen($server, $request): void
    {
        ApplicationContext::getContainer()->get(\Redis::class)->set(self::REDIS_FD_USER_KEY . $request->fd, $request->fd, 60 * 60 * 24);
    }
}
